<?php

class PagesController extends AdminController
{
	// ------------------------------------------------------------------------------------

	public $title = 'Страницы';
	public $name = '/pages/';

	// ------------------------------------------------------------------------------------
	/**
	 * @return void
	 */
	public function actionIndex()
	{
		if(isset($_POST['delete']))
		{
			for($i = 0, $iLength = count($_POST['id']); $i < $iLength; $i ++)
			{
				$Page = PagesLib::i()->find(array('page_id' => intval($_POST['id'][$i])));
				$Page && $Page->delete();
			}
		}

		AdminHelper::updateFilter($this->name, Page::i()->attributeTypes());

		$order = AdminHelper::getOrder($this->name);
		$filter = AdminHelper::getFilter($this->name);

		$FilterCriteria = AdminHelper::getFilterCriteria($this->name, Page::i()->attributeTypes());

		$Pages = PagesLib::i()->findAll($FilterCriteria);

		$this->render('list', array(
			'data' => $Pages,
			'order' => $order,
			'filter' => $filter
		));
	}

	// ------------------------------------------------------------------------------------
	/**
	 * @return void
	 */
	public function actionAdd()
	{
		return $this->actionEdit();
	}

	// ------------------------------------------------------------------------------------
	/**
	 * @return void
	 */
	public function actionEdit($page_id = NULL)
	{
		$errors = array();

		if(!empty($page_id) && is_numeric($page_id))
		{
			$Page = PagesLib::i()->find(array('page_id' => intval($page_id)));
		}
		else
		{
			$Page = new Page();
		}

		if(!empty($_POST))
		{
			$Page->setAttributes($_POST);
			if($Page->save())
			{
				//$this->redirect($this->name, 303);
			}
			else
			{
				$errors = $Page->getErrors();
			}
		}

		$this->render('edit', array(
			'data' => $Page,
			'errors' => FormHelper::prepareErrors($errors)
		));
	}
	
	// ------------------------------------------------------------------------------------
	/**
	 * @return void
	 */
	public function actionDelete($page_id = NULL)
	{
		if(empty($page_id) || !is_numeric($page_id))
		{
			$this->redirect($this->name);
			return;
		}

		$page_id = intval($page_id);
		$Page = PagesLib::i()->find(array('page_id' => $page_id));
		$Page && $Page->delete();
		$this->redirect($this->name);
	}

	// ------------------------------------------------------------------------------------
}